package com.luzhikun.downLoad_2;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author Rookie Coder
 * @Description
 * @Date
 **/
public class DownLoadServelt extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 修改响应的头部属性content-disposition值为attachment
        String fileName="梦中情人";
        // 打散
        byte[] bytes1 = fileName.getBytes("UTF-8");
        // 组装
        fileName=new String(bytes1,"ISO8859-1");
        resp.setHeader("content-disposition","attachment;fileName="+ fileName);

        // 获取连接服务端资源的输入流
        InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/resources/2.jpg");
        // 获取输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        // 将输入流中的数据写入到输出流中
        int len=-1;
        byte[] bytes=new byte[1024];
        while ((len= resourceAsStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        // 关闭流
        outputStream.close();
        resourceAsStream.close();

    }
}
